<template>
  <div class="weixinAuthInfo">
    <!-- 微信授权 -->
    <p class="title font16" v-if="type === 'add'">{{$t('configLazyLoad.channel.wexinTip20')}}</p>
    <!-- 微信基本信息 -->
    <div class="header">
      <img :src="data.head_img">
      <div class="headercontent">
        <p class="font14 weixintitle">{{$t('login.weixin')}}</p>
        <p style="margin: 3px 0;">{{$t('configLazyLoad.channel.wexinTip21')}}：{{data.alias}}</p>
        <p>{{$t('configLazyLoad.channel.wechatName')}}：{{data.nick_name}}</p>
      </div>
    </div>
    <div class="form">
      <el-form :model="data" labelPosition="left"  label-width="160px" style="text-align: left" ref="infoform">
        <!-- 是否启用日程 -->
        <el-form-item v-show="configType === 'config'" :label="$t('configLazyLoad.channel.wexinTip22')" prop="scheduleEnable">
          <el-radio-group v-model.trim="data.scheduleEnable">
            <el-radio :label="true">{{$t('configLazyLoad.public.reuse')}}</el-radio>
            <el-radio :label="false">{{$t('configLazyLoad.public.noReuse')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <p class="remark_title">{{$t('configLazyLoad.channel.wexinTip23')}}</p>
        <!-- 消息分发技能组 -->
        <el-form-item v-show="!data.scheduleEnable" :label="$t('configLazyLoad.interfaceConfig.msgGroup')" prop="to_peer">
          <el-select size="mini" v-model.trim="data.to_peer" :placeholder="$t('public.pleasePick')">
            <el-option
              v-for="(item, index) in peerOptions"
              :key="index"
              :label="item.DisplayName"
              :value="item.Exten"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 启用智能机器人 -->
        <el-form-item v-show="!data.scheduleEnable"  :label="$t('config.channel.isUseRobt')" prop="robot">
          <el-select size="mini" v-model.trim="data.robot" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
            <el-option value="">{{$t('public.pleasePick')}}</el-option>
            <el-option
              v-for="item in robotOptions"
              :key="item._id"
              :label="item.robot_name_new"
              :disabled="item.disabled"
              :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 机器人辅助座席   不启用日程并且有辅助座席的数据的时候才会展示 -->
        <el-form-item v-show="!data.scheduleEnable && aiRobots.length > 0"  :label="$t('configLazyLoad.channel.robotAssistId')" prop="robotAssistId">
          <el-select size="small" v-model.trim="data.robotAssistId" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
            <el-option value="">{{$t('public.pleasePick')}}</el-option>
            <el-option
              v-for="item in aiRobots"
              :key="item._id"
              :label="item.robot_name_new"
              :disabled="item.disabled"
              :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 是否开启触发词命中转人工 -->
        <el-form-item :label="$t('configLazyLoad.channel.turnTip3')" prop="openTriggerWord">
          <el-radio-group v-model.trim="data.openTriggerWord">
            <el-radio :label="true">{{$t('public.yes')}}</el-radio>
            <el-radio :label="false">{{$t('public.no')}}</el-radio>
          </el-radio-group>
          <question-tooltip
                  class="wechatTootip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.turnTip4')">
          </question-tooltip>
        </el-form-item>
        <!-- 转人工触发词 -->
        <el-form-item :label="$t('config.channel.userPeopleWord')" prop="convertWords">
          <el-input size="mini" v-model.trim="data.convert_words" :placeholder="$t('configLazyLoad.channel.turnTip5')"></el-input>
          <question-tooltip
                  class="wechatTootip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.turnTip6')">
          </question-tooltip>
        </el-form-item>
        <!-- 欢迎语推送时机 -->
        <el-form-item v-show="!data.scheduleEnable" :label="$t('config.channel.sendWelcomeMsg')" prop="welcomePushTime" style="text-align: left">
          <el-radio-group v-model="data.welcomePushTime" @change="pushTimeChange">
            <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
            <el-radio class="radio welcome-radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 欢迎语 -->
        <el-form-item v-show="!data.scheduleEnable"  :label="$t('config.channel.welcomeMsg')" prop="welcome_msg">
          <span class="remark">{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
          <question-tooltip
            class="wechatTootip"
            :direction="'bottom'"
            :tipContent="$t('configLazyLoad.channel.webStyleTip6')">
          </question-tooltip>
          <div class="placeholder_box">
            <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
              {{place.content}}
              <i class="iconfont icon-zhankai"></i>
            </dl>
          </div>
          <el-input size="mini" type="textarea" v-model="data.welcome_msg"></el-input>
        </el-form-item>
        <!-- 是否启用满意度评价 -->
        <el-form-item :label="$t('config.channel.isUseSatisfaction')" prop="csr" style="text-align: left">
          <el-radio class="radio statis-radio" v-model.trim="data.webchat_csr" :label="true">{{$t('config.channel.enabled')}}</el-radio>
          <el-radio class="radio" v-model.trim="data.webchat_csr" :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
        </el-form-item>
        <!-- 开发者密码(secret):-->
        <el-form-item :label="$t('config.channel.dvePwd')" prop="csr" style="text-align: left">
             <el-input  v-model.trim="data.appSecret" type="password"></el-input>
        </el-form-item>
        <el-form-item :label="$t('config.channel.authorizationPush')" prop="convertWords">
          <el-radio-group v-model.trim="data.snsapiUserinfoFlag">
             <el-radio class="radio statis-radio"  :label="true">{{$t('public.yes')}}</el-radio>
          <el-radio class="radio"  :label="false">{{$t('public.no')}}</el-radio>
          </el-radio-group>
          <question-tooltip
                  class="wechatTootip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.turnTip8')">
          </question-tooltip>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <el-button class="primary_btn" @click.stop="backPreviousStep()" v-if="type === 'add'">{{$t('config.channel.prevStep')}}</el-button>
      <el-button type="primary" class="primary_btn" @click.stop="saveSet()">{{type === 'add' ? $t('public.nextStep'):$t('public.save')}}</el-button>
    </div>
  </div>
</template>

<script>
  import { deepClone } from '@/utils/m7Utils'
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  export default {
    name: 'weixinAuthInfo',
    components: {
      questionTooltip
    },
    data () {
      return {
        data: {},         //  微信数据
        peerOptions: [],  //  技能组列表
        robotOptions: [], //  机器人列表
        aiRobots: [],     //  机器人辅助座席列表
        placeholderArr: [ //  欢迎语占位符
//          {
//            content: '访客ID：userId',
//            data: 'userId'
//          },
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ]
      }
    },
    props: ['weixindata', 'type'],
    computed: {
//      区分设置和简单版设置的标志
      configType () {
        let paths = this.$route.path.split('/')
        return paths[2]
      }
    },
    methods: {
//      机器人&&智能机器人的select下拉框出现时获取机器人列表
      robotSelectShow (show) {
        if (show) {
          this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
            if (res2 && res2.success && res2.data && res2.data.length > 0) {
              let aiRobot = res2.data
              let allRobot = this.robotOptions
              aiRobot.forEach((item1) => {
                item1._id = item1.Id
                item1.robot_name_new = item1.Nick
                let exist = allRobot.findIndex((all) => {
                  return all.Id === item1.Id
                })
                if (exist === undefined) {
                  allRobot.push(item1)
                } else {
                  allRobot.splice(exist, 1, item1)
                }
              })
              this.aiRobots = aiRobot
              this.robotOptions = allRobot
            }
          })
        }
      },
//     返回微信列表
      backPreviousStep () {
        this.$emit('preStep')
      },
//      保存
      saveSet () {
         if(this.data.snsapiUserinfoFlag&&!this.data.appSecret){
          this.$message.error(this.$t('configLazyLoad.channel.robotError5'))
          return
        }
        if (this.peerOptions.length === 0) {
          this.$message.error(this.$t('configLazyLoad.channel.robotError4'))
          return
        }
        this.$refs.infoform.validate((valid) => {
          if (valid) {
            let data = this.data
            if (!data.scheduleEnable) {
              if (!data.to_peer) {
                this.$message.error(this.$t('configLazyLoad.channel.webStyleTip64'))
                return
              }
              if (data.robot === '') {
                data.robotType = ''
              } else {
                this.robotOptions.forEach((item) => {
                  if (item._id === data.robot) {
                    if (item.Nick) {
                      data.robotType = item.robotType
                    } else {
                      data.robotType = item.robot_type_new
                    }
                  }
                })
              }
//          机器人辅助座席，增加assistRobotType参数
              this.aiRobots.map((item) => {
                if (data.robotAssistId === item._id) {
                  if (data.robotAssistId !== '') {
                    this.$set(data, 'assistRobotType', item.robotType)
                  } else {
                    this.$set(data, 'assistRobotType', '')
                  }
                }
              })
              data.robot = data.robot ? data.robot : ''
            }
            this.$store.dispatch('UpdateWeChatAuth', data).then((req) => {
              if (req.success) {
                this.$message.success(this.$t('business.updateSuccess'))
                this.$emit('saveDone')
              }
            })
          }
        })
      },
      //  更改欢迎语推送时机，改变欢迎语占位符展示
      pushTimeChange (data) {
        if (data === 'access') {
          this.placeholderArr = [
//            {
//              content: '访客ID：userId',
//              data: 'userId'
//            },
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }
          ]
          let str = ''
          if (this.data.welcome_msg) {
            str = deepClone(this.data.welcome_msg)
          }
          str = str.replace(/\{agent\}/g, '')
          str = str.replace(/\{agentName\}/g, '')
          this.data.welcome_msg = str
        } else if (data === 'claim') {
          this.placeholderArr = [
//            {
//              content: '访客ID：userId',
//              data: 'userId'
//            },
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }, {
              content: this.$t('configLazyLoad.channel.agent'),
              data: 'agent'
            }, {
              content: this.$t('configLazyLoad.channel.agentName'),
              data: 'agentName'
            }, {
              content: this.$t('configLazyLoad.channel.agentNickName'),
              data: 'agentNickName'
            }, {
              content: this.$t('configLazyLoad.channel.agentPhone'),
              data: 'agentPhone'
            }
          ]
        }
      },
//      点击添加欢迎语
      addPlaceholder (msg) {
        this.data.welcome_msg += '{' + msg + '}'
      }
    },
    mounted () {
//      初始化数据
      this.data = deepClone(this.weixindata)
//      设置欢迎语菜单选项
      this.pushTimeChange(this.data.welcomePushTime)
//      兼容老数据，是否启用满意度评价增加默认值
      if (!this.data.webchat_csr) {
        this.$set(this.data, 'webchat_csr', false)
      }
      if (!this.data.snsapiUserinfoFlag) {
        this.$set(this.data, 'snsapiUserinfoFlag', false)
      }
//      兼容老数据，欢迎语推送时机增加默认值
      if (!this.data.welcomePushTime) {
        this.$set(this.data, 'welcomePushTime', 'access')
      }
//      兼容老数据，欢迎语推送时机增加默认值
//      if (!this.data.welcomeMsg) {
//        this.$set(this.data, 'welcomeMsg', '')
//      }
//      兼容老数据，启用机器人增加默认值
      if (!this.data.robot) {
        this.$set(this.data, 'robot', '')
      }
//      兼容老数据，机器人辅助座席增加默认值
      if (!this.data.robotAssistId) {
        this.$set(this.data, 'robotAssistId', '')
      }
//      兼容老数据，机器人辅助座席增加默认值
      if (!this.data.to_peer) {
        this.$set(this.data, 'to_peer', '')
      }
//      兼容老数据，是否启用日程增加默认值
      if (!this.data.scheduleEnable) {
        this.$set(this.data, 'scheduleEnable', false)
      }
//      兼容老数据，是否启用日程增加默认值
      if (!this.data.welcome_msg) {
        this.$set(this.data, 'welcome_msg', '')
      }
//      数据初始化openTriggerWord（是否开启触发词命中转人工）值默认为true
      if (this.data.openTriggerWord === undefined) {
        this.$set(this.data, 'openTriggerWord', true)
      }
//      获取邮件技能组
      this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
        let mailQueues = this.$getCache('mailQueues')
        if (!mailQueues || mailQueues.length === 0) {
          return
        }
        this.peerOptions = mailQueues || []
      })
//      获取机器人列表
      this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
        let robotConfig = this.$getCache('robotConfig')
        this.robotOptions = robotConfig || []
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
            })
            this.aiRobots = aiRobot
            let configArr = []
            this.robotOptions.forEach((config) => {
              if (config.robot_type !== 'didi') {
                configArr.push(config)
              }
            })
            this.robotOptions = configArr.concat(this.aiRobots)
          }
        })
      })
      // 判断小七是否回显
      if (this.$store.state.isM7RobotOpen === false) {
        if (this.data.robot === '5825a500dfe52d5edc6e36c9') {
          this.data.robot = ''
        }
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .weixinAuthInfo
    width 460px
    margin 0 auto
    .title
      margin 10px 0
      text-align center
    .header
      text-align center
      border 10px solid #f1f1f1
      padding 17px 7px
      img
        width 60px
        height 60px
        vertical-align middle
      .headercontent
        display inline-block
        vertical-align middle
        text-align left
        margin-left 10px
    .weixintitle
      font-weight 600
    .form
      margin 20px 0
      .el-form-item .el-form-item__content
        text-align left
      .el-select
        width 100%
      .wechatTootip
        position absolute
        right -25px
    .footer
      text-align center
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height:16px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
  .remark_title
    color #3b5998
    font-size 12px
</style>
